package com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.repository;

import com.aliyun.gts.bpaas.middleware.mq.api.model.MqPayload;
import com.iwhalecloud.citybrain.flow.platform.manager.application.common.context.MqMessageContext;
import com.iwhalecloud.citybrain.flow.platform.manager.application.common.context.ProcessItem;
import com.iwhalecloud.citybrain.flow.platform.manager.application.common.enums.MqProcessTypeEnum;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.impl.MqProducer;
import com.iwhalecloud.citybrain.flow.platform.manager.application.utils.SpringUtils;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.User;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowDeploySendMessageRepository;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.repository.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Service - 流程部署发送mq消息
 *
 * @author lzb
 * @date 2021-12-03 18:56
 */
@Service
@Slf4j
public class FlowDeploySendMessageRepositoryImpl implements FlowDeploySendMessageRepository {

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private UserRepository userRepository;

    @Override
    public void flowDeploySendMessage(String modelId) {
        Model model = repositoryService.getModel(modelId);
        if (model != null) {
            try {
                ProcessItem processItem = new ProcessItem();
                User user = userRepository.getCurrentUser();
                processItem.setApplyUserId(user.getUserCode());//发起人id
                processItem.setApplyUserName(user.getUserName());//发起人名称
                processItem.setDeployId(model.getDeploymentId());//部署id
                processItem.setProcessInstanceVersion(String.valueOf(model.getVersion()));//部署流程版本
                processItem.setProcessInstanceName(model.getName());//流程名称
                processItem.setProcessInstanceKey(model.getKey());//流程编码
                MqMessageContext messageContext = MqMessageContext.builder().payload(MqPayload.make(processItem))
                        .tag(MqProcessTypeEnum.DEPLOY.getType())
                        .messageKey(model.getId())
                        .build();
                //这里可以走异步，前面拼接参数还是得同步
                doSendMessage(messageContext);
            } catch (Throwable e) {
                log.error("build messageContext error:", e);
            }
        }
    }

    private void doSendMessage(MqMessageContext messageContext) {
        MqProducer producer = SpringUtils.getBean(MqProducer.class);
        producer.sendMessage(messageContext);
    }
}
